import Taro from '@tarojs/taro';

export const toast = (msg: string) => {
  if (!msg) {
    return;
  }
  Taro.showToast({
    title: typeof msg === 'object' ? JSON.stringify(msg) : msg,
    icon: 'none',
  });
};

let systemInfo;
export const isIphoneX = () => {
  systemInfo = systemInfo || Taro.getSystemInfoSync();
  if (process.env.TARO_ENV === 'rn') {
    return require('react-native').Platform.OS !== 'android' && systemInfo.safeArea?.bottom < systemInfo.screenHeight;
  } else {
    const phoneMarks = ['iPhone X', 'iPhone 11', 'iPhone 12', 'iPhone 13', 'iPhone 14', 'iPhone 15'];
    const { model = '' } = systemInfo;
    for (let i = 0, l = phoneMarks.length; i < l; i++) {
      if ((model || '').startsWith(phoneMarks[i])) return true;
    }
    return false;
  }
};

interface TimeOutTask extends Promise<TimeOutTask> {
  /** 清除定时器 */
  clear(): void;
}

/** @param time 倒计时时间, ms */
export const asyncTimeOut = (time: number): TimeOutTask => {
  let resolveFunc;
  let rejectFunc;
  const pro = new Promise((resolve, reject) => {
    resolveFunc = resolve;
    rejectFunc = reject;
  }) as TimeOutTask;
  const timer = setTimeout(() => resolveFunc({ code: 200, message: '倒计时结束', type: 'timeout' }), time);
  pro.clear = () => {
    clearTimeout(timer);
    rejectFunc({ code: 500, message: '清除倒计时' });
  };
  return pro;
};

export const noop = () => {};

/**
 * 获取Platform类型，主要用于支付请求的时候获取不同的支付类型
 * @returns {string} app APP端 | weapp 微信小程序 | wechat 微信公众号 | wap h5端
 */
export const getPlatform = () => {
  switch (process.env.TARO_ENV) {
    case 'rn':
      return 'app';
    case 'h5':
      // @ts-ignore
      const ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return 'wechat';
      } else {
        return 'wap';
      }
    default:
      return process.env.TARO_ENV;
  }
};

export const stopPropagation = e => {
  e?.stopPropagation?.();
};

export const uuid = function () {
  const s: string[] = [];
  const hexDigits = '0123456789ABCDEF';
  for (let i = 0; i < 32; i += 1) {
    const index = Math.floor(Math.random() * 0x10);
    s[i] = hexDigits.substring(index, index + 1);
  }
  s[14] = '4'; // 版本4，伪随机数
  const index2 = (s[19] as any & 0x3) | 0x8;
  s[19] = hexDigits.substring(index2, index2 + 1);
  return s.join('');
};

/** formik错误处理，转成一维数组字符串 */
export function flatFormikErrors(errors: any) {
  let array: string[] = [];
  if (errors) {
    if (Array.isArray(errors)) {
      errors.forEach((item: any) => {
        array = array.concat(flatFormikErrors(item));
      });
    } else if (typeof errors === 'object') {
      Object.keys(errors).forEach(key => {
        const item = errors[key];
        array = array.concat(flatFormikErrors(item));
      });
    } else if (typeof errors === 'string') {
      array.push(errors);
    }
  }
  return array;
}
